import { defineStore } from 'pinia'
import { useMenuNavApi } from '@/api/sys/menu'
import { generateRoutes, constantMenu, dashboardMenu } from '@/router'
import { RouteRecordRaw } from 'vue-router'

import { useUserInfoApi } from '@/api/sys/user'
import menuJson from './new.json'
import menuJson2 from './new2.json'

// 后端菜单转换
const convertMenuToRoutes = (menus: any[]) => {
	const routes = []
	menus.forEach(menu => {
		var route = {}
		route = {
			id: menu.id,
			url: menu.href,
			name: menu.label,
			openStyle: 0,
			menuType: menu.menuType,
			menuCode: menu.menuCode,
			parentId: menu.parentId,
			icon: menu.parentId == '0' || menu.parentId == '-1' ? 'icon-appstore' : '',
			operationCode: menu.operationCode
		}
		if (menu.children) {
			route['children'] = convertMenuToRoutes(menu.children)
		}
		routes.push(route)
	})
	return routes
}

export const useRouterStore = defineStore('routerStore', {
	state: () => ({
		menuRoutes: [] as RouteRecordRaw[],
		searchMenu: [] as RouteRecordRaw[],
		routes: [] as RouteRecordRaw[]
	}),
	actions: {
		async getMenuRoutes() {
			// const { data } = await useMenuNavApi()
			const { data } = await useUserInfoApi()
			///	console.log("获取用户菜单：", data.menuList)
			//	const routes = generateRoutes(data)

			// 控制台菜单
			// console.log("本地数据json文件：", menuJson2)
			var addDynamicRoutes = []
			if (data.menuList.length > 0) {
				addDynamicRoutes = convertMenuToRoutes(data.menuList[0]['children']) // 动态菜单
			}

			const dashboardRoutes = generateRoutes(addDynamicRoutes)
			// const dashboardRoutes = generateRoutes(dashboardMenu) // 本地前面写的路由菜单
			this.menuRoutes = []
			this.menuRoutes.push(...dashboardRoutes)

			// 后端菜单
			//	this.menuRoutes.push(...routes)

			// 常量菜单
			// const constantRoutes = generateRoutes(constantMenu)

			// this.menuRoutes.push(...constantRoutes)

			return this.menuRoutes
		},
		setSearchMenu(routers: RouteRecordRaw[]) {
			this.searchMenu = routers
		},
		setRoutes(routers: RouteRecordRaw[]) {
			this.routes = routers
		}
	}
})
